package com.haoyun.mirage.auth.config;

import com.haoyun.common.config.FilterUrlsPropertiesConfig;
import com.haoyun.mirage.auth.provider.UserAuthenticationProvider;
import com.haoyun.mirage.auth.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.web.cors.CorsUtils;

/**
 * Created by twg on 2018/5/27.
 *
 */
@Configuration
@EnableWebSecurity
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class AuthenticationServerConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private FilterUrlsPropertiesConfig filterUrlsPropertiesConfig;

    @Autowired
    private UserAuthenticationProvider userAuthenticationProvider;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // @formatter:off
        http.formLogin().loginPage("/authentication/login").permitAll()
                .loginProcessingUrl("/authentication/login/process").permitAll().and()
                // 对请求进行认证
                .authorizeRequests().antMatchers("/authentication/removeToken").permitAll()
                // 所有请求需要身份认证
                .anyRequest().authenticated()
                // 关闭csrf验证
                .and().csrf().disable()
                .anonymous().disable()
                .cors().disable()
                .httpBasic();
        // @formatter:on
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        // 所有请求 都放行
        filterUrlsPropertiesConfig.getAnon().stream().forEach(url -> {
            web.ignoring().antMatchers(url);
        });
    }


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 使用自定义身份验证组件
        auth.authenticationProvider(userAuthenticationProvider);
    }
}
